/*
* Copyright 2010 ANDAGO INGENIERIA S.L.
*
* Licensed under the EUPL, Version 1.1 only (the "Licence");
* You may not use this work except in compliance with the
* Licence.
* You may obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl
*
* Unless required by applicable law or agreed to in
* writing, software distributed under the Licence is
* distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
* See the Licence for the specific language governing
* permissions and limitations under the Licence.
*/

package com.andago.alohaui;



import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


public class AlohaMainUI extends Activity {
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		
		super.onCreate(savedInstanceState);
		
	
		 final String[] SELECTION = new String[] {
					this.getString(R.string.measures_selection), 
					this.getString(R.string.devices_selection)

			    };
		 
		setContentView(R.layout.main_aloha);
		
		ListView lv = (ListView) findViewById(R.id.list_measures);
		lv.setAdapter(new ArrayAdapter<String>(this, R.layout.fila, SELECTION));
		 
	    lv.setTextFilterEnabled(true);
	    
	    checkSettings();  
    
	    
	    lv.setSelection(0);
	   	      
      
	    lv.setOnItemClickListener(new OnItemClickListener() {
	        public void onItemClick(AdapterView<?> parent, View view,
	            int position, long id) {
	        	
	        		if (SELECTION[position].equals(getString(R.string.measures_selection))){
	        			Intent intent = new Intent(AlohaMainUI.this,MeasuresListActivity.class);
	        			intent.putExtra(getString(R.string.selection_bundle), SELECTION[position]);
	        			startActivityForResult(intent,0);        			
	        			
	        		}
	        		if (SELECTION[position].equals(getString(R.string.devices_selection))){
	        			
	        			if(startingService()){
		        			Intent intent = new Intent(AlohaMainUI.this,DevicesActivity.class);
		        			intent.putExtra(getString(R.string.selection_bundle), SELECTION[position]);
		        			startActivityForResult(intent,0);
		        		}
	        			
	        		}		        	
	        }
	      });
    
		
	}

	
	private void checkSettings(){
		
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		String userAndago = settings.getString("ausername", "");
		String userGoogle = settings.getString("gusername", "");
		String passGoogle = settings.getString("gpassword", "");
		
		if ((userAndago == "") && ((userGoogle == "") || (passGoogle == ""))){
			
			
			AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
			localBuilder.setMessage(getString(R.string.no_users))
			       .setCancelable(false)
			       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int id) {
			        	    dialog.cancel();
			   				Intent intent = new Intent(AlohaMainUI.this, SettingsActivity.class);
			   				startActivity(intent);		
			           }
			       });
			       
			AlertDialog alert = localBuilder.create();
			alert.show();
	
		}		

	}
	
	
	
	/* Adding MENU option */

    @Override
	public boolean onCreateOptionsMenu (Menu menu){
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu, menu);
    	return true;
    }
    
    /* (non-Javadoc)
     * @see android.app.Activity#onMenuItemSelected(int, android.view.MenuItem)
     */
    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
            Intent intent;
            switch(item.getItemId()) {
                    case R.id.settings:
                            intent = new Intent(this, SettingsActivity.class);
                            startActivity(intent);
                            break;
                    case R.id.exit:
                    		//AlohaMainUI.this.finish();
                    		System.exit(0);
                    		break;
                    case R.id.about:
     
                    	AlertDialog.Builder builder;
                       	
                    	Context mContext = getApplicationContext();                    	
                    	LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);                    	
                    	View layout = inflater.inflate(R.layout.about, (ViewGroup) findViewById(R.layout.main_aloha));
                    	
    
                    	builder = new AlertDialog.Builder(this);
                    	builder.setView(layout);
                    	builder.setCancelable(false);
                    	builder.setPositiveButton("OK", new DialogInterface.OnClickListener(){ 
                    		public void onClick(DialogInterface dialog, int id){
                    			dialog.cancel();
                    		}
                    	});
                    	
                    	AlertDialog alert = builder.create();
                    	alert.show();
                            break;
            }
            return true;
    }
	

   
     
	 private boolean startingService (){
		 
		  boolean connected = false;
		 
	    	// Make sure the service is started.  It will continue running
	        // until someone calls stopService().
	        // We use an action code here, instead of explictly supplying
	        // the component name, so that other packages can replace
	        // the service.
		 
		 
		    // checking whether the activity is already started
	        ActivityManager a = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
	        List<RunningServiceInfo> servicesInfo= a.getRunningServices(15);
	        
	        
	        for (RunningServiceInfo ele : servicesInfo) {
	        	
	        	System.err.println("Process : " + ele.process);
	        	
		        if (ele.process.equals("es.libresoft.openhealth.android:remote")) {
		        	
		        	System.err.println("Ha entrado Procesos : " + ele.process);		        	
		        	if(!ele.started){
		        		System.err.println("service not started!!");
	        	    	Intent intentDroid = new Intent(getString(R.string.droidEvent));
	        	    		
	        	    	if (startService(intentDroid)==null){
	        	    		Toast toast = Toast.makeText(this, R.string.not_found_service, Toast.LENGTH_SHORT);
	        	    		toast.show();
	        	    		
	        	    	}else{
	        	    		connected=true;
	        	    		System.err.println("service started!!");
	        	    	}
	        	    }else{
	        	    	connected=true;	        	    	        	    	
	        	    	System.err.println("service already started!!");
	        	    	
	        	    }
	        	    	
		        }
	         } 	

	        if (!connected){
	        	System.err.println("service not started!!");
    	    	Intent intentDroid = new Intent(getString(R.string.droidEvent));
    	    	if (startService(intentDroid)==null){
    	    		Toast toast = Toast.makeText(this, getString(R.string.not_found_service), Toast.LENGTH_SHORT);
    	    		toast.show();
    	    		
    	    	}else
    	    	{
    	    		connected=true;
    	    		System.err.println("service started!!");
    	    	}	
	         }
	        
	        return connected;
	        	
	 }
	 
	 

	

	 @Override
		public void onStop(){
			super.onStop();
			this.finish();
		}
		@Override
		public void onDestroy(){
			super.onDestroy();
		}
}

